<?php
/**
 *  商品服务器层
*/

namespace app\api\service;


use app\admin\model\Algorithm;
use app\api\model\ProductBrand;
use app\common\ApiClient;
use app\common\RedisClient;
use app\facade\Basic;
use app\api\model\Customer;
use app\api\model\Product as ProductModel;
use think\facade\Cache;
use think\facade\Config;


class Product
{
    /**
     *  获取商品列表
    */
    public function getProductList ($param)
    {











        print_r($PriceList);
        die;


    }
   public function select($lang)
   {
       $redis = New RedisClient();
       $redisData = [];
       $brandList = $redis->get('brandList');
       $coinList = $redis->get('coinList');
       $algorithmList = $redis->get('algorithmList');
       $redisData['brandList'] = $brandList?json_decode($brandList,true):[];
       $redisData['coinList'] = $coinList?json_decode($coinList,true):[];
       $redisData['algorithmList'] = $algorithmList?json_decode($algorithmList,true):[];

       $common = new Common();
       $content = [];
       foreach ($redisData as $v){
            foreach ($v as &$vv){
                $content[md5($vv['name'])] = $vv['name'];
            }
       }
       $tanslate = $common->translate(['content'=>json_encode($content),'target_language'=>$lang]);
       if(isset($tanslate['code']) && $tanslate['code'] == 0){
           foreach ($redisData as &$v){
               foreach ($v as &$vv){
                   $vv['name'] = $tanslate['data'][md5($vv['name'])] ?? $vv['name'];
               }
           }
       }
       return Basic::data(0,'common.success',$redisData);
   }
   public function historyIncome($params)
   {
       #验证参数
       if(!isset($params['id']) || !$params['id'] || !isset($params['number']) || !$params['number'] || !isset($params['coinName']) || !$params['coinName']){
           return Basic::data( 100002, 'common.parameterError');
       }
       $productInfo = ProductModel::where('id',$params['id'])->find()->toArray();
       $model_id = $productInfo['model_id'] ?? '';
       if(!$model_id){
           return Basic::data( 0, 'common.success',[]);
       }
       $unit = (new ProductModel())->getAttributes('computing_unit') ?? [];
       #formate repuest param
       $domain = Config::get('domain')['prod']['erpapi'];
       $apiClient = new ApiClient($domain);
       $param = [
           "symbol" =>(string)$params['coinName'],
           "number" =>$params['number'],
           "hashrate" =>$productInfo['hashrate'],
           "unit" =>$unit[$productInfo['computing_unit']],
       ];
       $data = $apiClient->get('/api/support/mta/history-income-symbol',  ['body' =>  json_encode($param)]);
        $return = [];
       if (isset($data['status']) &&  $data['status'] == 'success') {
           foreach ($data['data'] as &$datum)
           {
               $datum['time'] = date('Y-m-d' ,strtotime($datum['time']));
           }
           usort($data['data'], function($a, $b) {
               return strtotime($a['time']) - strtotime($b['time']);
           });
           $return = $data['data'];
       }
       return Basic::data( 0, 'common.success',$return);
   }

    /**
     * 矿机收益计算
     */
    public function profit($params,$lang) :array
    {
        #验证参数
        if(!isset($params['type']) || !in_array($params['type'],[0,1,2])){
            return Basic::data( 100002, 'common.parameterError');
        }
        $redis = New RedisClient();
        #处理场景 根据不同场景 拿不同的商品信息
        $pid = $params['pid'] ?? 0;
        $func = '';
        #批量获取商品信息
        $product = new ProductModel();
        if($params['type'] == 1){
            $func = 'getRecommendList';
        }elseif ($params['type'] == 2){
            $redisKey = 'getProductList:'.$lang;
            $redisData = $redis->get($redisKey);
            if($redisData){
                $redisData = json_decode($redisData,true);

                if($redisData){
                    foreach ($redisData as $k=>&$redisDatum){
                        if(isset($params['brand']) && $params['brand']){
                            $brands = explode(',',$params['brand']);
                            if(!in_array($redisDatum['brand_name'],$brands)){
                                unset($redisData[$k]);
                                continue;
                            }
                        }
                        if(isset($params['algorithm']) && $params['algorithm'] && $params['algorithm'] != 'all' ){
                            $coins_data = $redisDatum['coins_data'];
                            $algorithms = explode(',',$params['algorithm']);
                            foreach ($coins_data as $algorithm_key =>$coins_datum){
                                $is_del = true;
                                foreach ($algorithms as $algorithm){
                                    if($algorithm == $coins_datum['algorithm']){
                                        $is_del = false;
                                    }
                                }
                                if($is_del){
                                    unset($coins_data[$algorithm_key]);
                                }
                            }
                            if(empty($coins_data)){
                                unset($redisData[$k]);
                                continue;
                            }
                            $redisDatum['coins_data'] =  array_values($coins_data);
                        }
                        if(isset($params['coin'])  && $params['coin'] && $params['coin'] != 'all'){
                            $coins_data = $redisDatum['coins_data'];
                            $coins = explode(',',$params['coin']);
                            foreach ($coins_data as $coin_key =>$coins_datum){
                                $is_del = true;
                                foreach ($coins as $coin){
                                    if($coin == $coins_datum['short_name']){
                                        $is_del = false;
                                    }
                                }
                                if($is_del){
                                    unset($coins_data[$coin_key]);
                                }
                            }
                            if(empty($coins_data)){
                                unset($redisData[$k]);
                                continue;
                            }
                            $redisDatum['coins_data'] =  $coins_data;
                        }
                    }
                }
                return Basic::data(0,'common.success',array_values($redisData));
            }else{
                return Basic::data(0,'common.success',[]);
            }

        }

        $produtList = $product->getProductInfoForProfit($pid,$func);
        if(empty($produtList)){
            return Basic::data(0,'common.success',[]);
        }

        #调别的系统接口 拿到收益的信息
        $profitList = $this->getProfitInfo($produtList);

        if(empty($profitList)){
            return Basic::data(0,'common.success',[]);
        }
        #格式化数据  按前端友好数据格式返回
        $profitList = $this->profitFormate($profitList,$produtList,$lang);

        return Basic::data(0,'common.success',$profitList);
    }
    /**
     * 请求三方接口 存redis
     */
    public function getProfitInfoForCache($produtList)
    {
        if (empty($produtList)) {
            return [];
        }

        #formate repuest param
        $domain = Config::get('domain')['prod']['erpapi'];
        $apiClient = new ApiClient($domain);
        $redis = New RedisClient();
        $return = [];

        foreach ($produtList as $v) {
            $key = $this->getRedisKey($v['id']);
            #过滤数据有问题的数拒
            if (empty($v['hashrate']) || empty($v['unit'])) {
                continue;
            }
            $param = [];
            if ($v['algorithm']) {
                foreach (explode(',', $v['algorithm']) as $item) {
                    $algorithm = (new Algorithm())->getAttributes('algorithm')[$item] ?? '';
                    if (!$algorithm) {
                        continue;
                    }
                    $param[] = [
                        'id' => $v['id'],
                        'hashrate' => $v['hashrate'],
                        'unit' => $v['unit'],
                        'algorithm' => $algorithm,
                    ];
                }
            }
            if($param){
                $data = $apiClient->post('api/support/mta/profit', ['body' => json_encode(['body' => $param])]);
                if (!isset($data['status']) || $data['status'] != 'success') {
                    continue;
                }
                if(isset($data['data'][0]) && $data['data'][0]){
                    $redis->set($key, json_encode($data['data'][0]));
                    $redis->setExpiry($key, 3600);
                    $return[] = $data['data'][0];
                }

            }
        }
        return $return;
    }

    /**
     * 请求三方接口 存redis
     */
    public function formateForCache($data,$produtList,$lang)
    {
        $return = [];
        if (empty($produtList)) {
            return [];
        }
        $pids = array_column($produtList, 'id');
        $brands = array_column($produtList, 'brand');
        $brandInfo = ProductBrand::whereIn('id',$brands)->select()->toArray();
        $brandInfo = array_column($brandInfo,null,'id');

        $pmInfo = \app\api\model\ProductMerge::whereIn('primary_pid',$pids)->select()->toArray();
        $pmInfo = array_column($pmInfo,null,'primary_pid');

        $product = new ProductModel();
        $minPrice = $product->getMinPrice($pids);
        $redis = New RedisClient();
        foreach ($data as $v){
            $formateData = ['data'=>[$v]];
            $redisData = $this->profitFormateForCrontab($formateData,$produtList,$lang,$brandInfo,$minPrice,$pmInfo);
            $key = $this->getRedisKey($v['id'],$lang);
            $redis->set($key, json_encode($redisData[0]));
            $redis->setExpiry($key, 3600);
            $return[] = $redisData[0];
        }
        return $return;
    }
    /**
     * 请求三方接口 拿到收益明细
     */
    private function getProfitInfo($produtList): array
    {
        if (empty($produtList)) {
            return [];
        }
        $data = [];
        $redis = New RedisClient();

        foreach ($produtList as $v) {
            $key = $this->getRedisKey($v['id']);
            $redisData = $redis->get($key);
            if (!$redisData) {
                continue;
            }
            $redisData =json_decode($redisData,true);
            $data['data'][] =  $redisData;
        }
        return $data;
    }
     /**
      * 格式化三方请求返回的数据
      *
      */
    private function profitFormateForCrontab($data, $produtList, $lang,$brandInfo,$minPrice,$pmInfo): array
    {
        if (!isset($data['data']) || empty($data['data'])) {
            return [];
        }
        #翻译支持语言
        $common = new Common();
        $return = [];
        $data = $data['data'];
        $produtList = array_column($produtList, null, 'id');

        #合并 product id 一样的数据
        foreach ($data as $v) {
            #商品id已存在
            if (isset($return[$v['id']])) {
                if (isset($v['coins_data']) && !empty($v['coins_data'])) {
                    #将algorithm 赋给每一个coins_data
                    $coins_data = $this->formateCoinData($v);
                    # 合并 coins_data
                    $return[$v['id']]['coins_data'] = array_merge($return[$v['id']]['coins_data'], $coins_data);
                }
                #只需要coins data 无需格式化商品数据
                continue;
            } else {
                if (isset($v['coins_data']) && !empty($v['coins_data'])) {
                    $v['coins_data'] = $this->formateCoinData($v);
                    unset($v['algorithm']);
                }
            }
            $release_date = '';
            if (isset($produtList[$v['id']]['release_date']) && $produtList[$v['id']]['release_date']) {
                // 直接从YYYYmm格式解析日期
                $date = \DateTime::createFromFormat('Ym', $produtList[$v['id']]['release_date']);
                if ($date instanceof \DateTime) {
                    // 格式化为 "M Y" (如: Jul 2025)
                    $release_date = $date->format('M Y');
                }
            }
            $power = $produtList[$v['id']]['power'] ?? 0;
            $unit = $produtList[$v['id']]['unit'] ?? '';
            $unit = explode('/', $unit)[0] ?? '';
            $v['efficiency'] = bcdiv((int)$power, $v['hashrate'], 2) . ' W/' . $unit;
            $v['cname'] = $produtList[$v['id']]['cname'] ?? '';
            # 翻译
            if ($v['cname']) {
                $tran = md5($v['cname']);
                $translate = [
                    'content' => json_encode([$tran => $v['cname']]),
                    'target_language' => $lang,
                ];
                $tran_return = $common->translate($translate);
                $v['cname'] = $tran_return['data'][$tran] ?? $v['cname'];
            }
            $v['power'] = $produtList[$v['id']]['power'] ?? '';
            $v['release_date'] = $release_date;
            $v['brand'] = $produtList[$v['id']]['brand'] ?? '';
            $v['brand_image'] = $brandInfo[$v['brand']]['image'] ?? '';
            $v['brand_name'] = $brandInfo[$v['brand']]['name'] ?? '';
            $v['producturlname'] = $pmInfo[$v['id']]['producturlname'] ?? '';
            $v['price'] =$minPrice[$v['id']] ?? 0;
            $return[$v['id']] = $v;
        }
        $return = array_values($return);
        return $return;
    }
    /**
     * 格式化三方请求返回的数据
     *
     */
    private function profitFormate($data, $produtList, $lang): array
    {
        if (!isset($data['data']) || empty($data['data'])) {
            return [];
        }
        $produtList = array_column($produtList, null, 'id');
        $pids = array_column($produtList, 'id');
        $redis = New RedisClient();
        foreach ($pids as $v){
            $key = $this->getRedisKey($v,$lang);
            $redisdata = $redis->get($key);
            if($redisdata){
                $return[]  = json_decode($redisdata,true);
            }

        }
        return $return;
    }
    /**
     * coin url 拼接
     */
    public function getCoinsUrl($name)
    {
        $name = urlencode($name);
        $url = 'https://mintheasic.oss-us-west-1.aliyuncs.com/coin-icon/64/%s.jpg?x-oss-process=image/auto-orient,1/resize,m_lfit,h_55';
        return sprintf($url,$name);
    }
    /**
     * 格式化币的收益数据
     */
    private function formateCoinData($data)
    {
        #将algorithm 赋给每一个coins_data
        $coins_data = $data['coins_data'];
        array_walk($coins_data, function(&$vv,$k,$v) {
            $vv['algorithm'] = $v['algorithm'];
            $vv['coin_url'] = $this->getCoinsUrl($vv['short_name']);
        },$data);
        return $coins_data;
    }

    private  function  getRedisKey($id,$lang='')
    {
        $str = 'product:profit:%d:%s';
        return sprintf($str,$id,$lang);
    }



}

